package com.finance.report.service;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.finance.base.constant.BaseConstants;
import com.finance.base.enums.StateEnum;
import com.finance.framework.lang.Page;
import com.finance.framework.lang.PageResultBO;
import com.finance.report.bean.pojo.LogisticsData;
import com.finance.report.bean.pojo.LogisticsErrorLog;
import com.finance.report.dao.LogisticsErrorLogMapper;
import com.finance.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class LogisticsErrorLogService implements ILogisticsErrorLogService{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private LogisticsErrorLogMapper logisticsErrorLogMapper;

    @Override
    public LogisticsErrorLog getById(Date signTime, Long id) {
        String tableName = this.getErrorTableName(signTime);
        return logisticsErrorLogMapper.getById(tableName,id);
    }

    @Override
    public List<Map> listAll(Date signTime){
        String tableName = this.getErrorTableName(signTime);
        return logisticsErrorLogMapper.listAll(tableName);
    }

    @Override
    public PageResultBO<LogisticsErrorLog> listByPage(Date signTime,Page page) {
        PageResultBO<LogisticsErrorLog> resultBO = new PageResultBO<LogisticsErrorLog>();
        String tableName = this.getErrorTableName(signTime);
        Map param = (Map) page.getParams();
        param.put("tableName",tableName);
        page.setParams(param);
        List<LogisticsErrorLog> list = this.logisticsErrorLogMapper.listByPage(page);
        resultBO.setDataList(list);
        resultBO.setPageSize(page.getPageSize());
        resultBO.setPageNo(page.getPageNo());
        resultBO.setTotalRecord(page.getTotalRecord());
        return resultBO;
    }

    @Override
    public boolean delete(Date signTime,Long id) {
        String tableName = this.getErrorTableName(signTime);
        return logisticsErrorLogMapper.delete(tableName,id) == 1;
    }

    @Override
    public boolean delete(Date signTime, String wayBillNum) {
        String tableName = this.getErrorTableName(signTime);
        boolean result = false;
        try {
            result = logisticsErrorLogMapper.deleteByWaybillNum(tableName,wayBillNum) == 1;
        } catch (Exception e) {
            logger.error("运单错误日志删除异常: {}",e.getMessage());
        }
        this.logger.info("根据运单号删除结果：{} 运单号：{}",String.valueOf(result), wayBillNum);
        return result;
    }

    @Override
    public boolean addErrorLog(LogisticsData logisticsData,String errorReason,String errorType){
        LogisticsErrorLog logisticsErrorLog = new LogisticsErrorLog();
        logisticsErrorLog.setWaybillNum(logisticsData.getWaybillNum());
        try{
            logisticsErrorLog.setRequestLogInfo(this.objectMapper.writeValueAsString(logisticsData));
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(),e);
        }
        logisticsErrorLog.setErrorType(errorType);
        logisticsErrorLog.setErrorReason(this.limitInfo(errorReason));
        logisticsErrorLog.setState(StateEnum.Valid.getState());
        logisticsErrorLog.setMonth(DateUtils.formatDate(logisticsData.getSignTime(),"yyyy-MM"));
        String tableName = this.getErrorTableName(logisticsData.getSignTime());
        try{
            int row = this.logisticsErrorLogMapper.add(tableName,logisticsErrorLog);
            return row == 1;
        }catch (Exception e){
            this.logger.error("重复插入errorlog:{}",logisticsData.getWaybillNum());
        }
        return false;
    }

    /**
     * 限制存入字段的数据长度
     * @param info
     * @return
     */
    public String limitInfo(String info){
        return StringUtils.isNotBlank(info) && info.length() > 1024 ? info.substring(0,1023) : info;
    }

    /**
     * 获取操作表名
     * @return
     */
    public String getErrorTableName(Date signTime){
        return BaseConstants.SYSCONFIG_KEY_LOGISTICERROR_TABLE + DateUtil.dateFormat(signTime,"yyMM");
    }

    @Override
    public List<LogisticsErrorLog> getByMonth(Date month){
        String tableName = this.getErrorTableName(month);
        String monthStr = DateUtil.dateFormat(month,DateUtil.YEAR_AND_MONTH_FORMAT);
        return logisticsErrorLogMapper.getByMonth(tableName,monthStr);
    }
}
